class_name EquipLightningBall
extends EquipmentBase

@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var search_area: Area2D = $SearchArea
@onready var equip_sprite: Sprite2D = $Sprite
@export var shoot_interval: float = 1.0
var shoot_timer: float = 0


func _ready() -> void:
	animation_player.play("anim")
	shoot_timer = shoot_interval


func _physics_process(delta: float) -> void:
	shoot_timer -= delta
	if shoot_timer <= 0:
		shoot_timer = shoot_interval
		shoot_lightning_ball_bullet_magic()


func shoot_lightning_ball_bullet_magic():
	var areas = search_area.get_overlapping_areas()
	if areas.size() <= 0: return
	
	var config = item_data.item_config
	var player = holder as Player
	
	for area in areas:
		var source = area.source
		
		var attack_target_position = source.global_position
		if source is UnitBase:
			attack_target_position = source.ray_cast_point.global_position
		var target_dir = (attack_target_position - equip_sprite.global_position).normalized()
		
		var has_obstacle = GlobalUtils.raycast_to(equip_sprite.global_position, attack_target_position, 1)
		if has_obstacle: continue
	
		var magic = (ResourceManager.get_resource("particle_lightning_ball_bullet") as PackedScene).instantiate() as ParticleLightningBallBullet
		
		magic.attack = config.attack
		magic.critical_rate = config.critical_rate
		magic.critical_bonus = config.critical_bonus
		magic.knockback = config.knockback
		magic.sender = holder
		magic.dir = target_dir
		magic.speed = 200
		magic.life_time = 3.0
		
		if config.attack_cam_shake:
			magic.hit_cam_shake_strength = config.attack_cam_shake_intensity
			magic.hit_cam_shake_duration = config.attack_cam_shake_duration
		
		player.level.particles_parent.add_child(magic)
		magic.global_position = equip_sprite.global_position
		magic.set_is_enemy(false)
		
		await get_tree().physics_frame
